package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

var clients = make(map[string]*Node)

type Node struct {
	Conn *websocket.Conn
	Data chan []byte
}

func Chat(c *gin.Context) {
	userId := c.Query("userId")
	friendId := c.Query("friendId")
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}
	if _, ok := clients[userId]; !ok {
		clients[userId] = &Node{
			Conn: conn,
			Data: make(chan []byte),
		}
		go ReadMsg(clients[userId], friendId)
		go Send(clients[userId])
	}
}
func ReadMsg(myNode *Node, friendId string) {

	for {
		_, data, err := myNode.Conn.ReadMessage()
		if err != nil {
			log.Println(err)
			return
		}
		friendNode := clients[friendId]
		friendNode.Data <- data
	}

}

func Send(myNode *Node) {
	for {
		select {
		case data := <-myNode.Data:
			err := myNode.Conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				log.Println(err)
				return
			}

		}
	}
}
